import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Input, 
  Button, 
  Space, 
  Tag, 
  message,
  Modal,
  Form,
  Select,
  DatePicker,
  Upload,
  Row,
  Col
} from 'antd';
import { 
  SearchOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined,
  UploadOutlined
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { history, useModel } from '@umijs/max';
import { getBooks, deleteBook, createBook } from '@/services/bookAPi';
import { getCategories } from '@/services/categoryApi';
import { BookItem } from '@/types/book';

const { Option } = Select;
const { RangePicker } = DatePicker;

const BookList: React.FC = () => {
  const [books, setBooks] = useState<BookItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [categories, setCategories] = useState<any[]>([]);
  const [searchForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteBookId, setDeleteBookId] = useState<number | null>(null);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [uploadFileList, setUploadFileList] = useState<any[]>([]);
  const [createBookForm] = Form.useForm();

  const { initialState } = useModel('@@initialState');

  // 获取图书列表
  const fetchBooks = async (params = {}) => {
    setLoading(true);
    try {
      const { current = 1, pageSize = 10 } = pagination;
      const searchParams = {
        page: current,
        page_size: pageSize,
        ...params,
      };

      const res = await getBooks(searchParams);
      setBooks(res.data.results);
      setPagination({
        ...pagination,
        total: res.data.count,
      });
    } catch (error) {
      message.error('获取图书列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const res = await getCategories();
      setCategories(res.data.results);
    } catch (error) {
      message.error('获取分类列表失败');
    }
  };

  useEffect(() => {
    fetchBooks();
    fetchCategories();
  }, [pagination.current, pagination.pageSize]);

  // 搜索
  const handleSearch = (values: any) => {
    const params = {
      ...values,
      publish_date_min: values.publish_date ? values.publish_date[0] : undefined,
      publish_date_max: values.publish_date ? values.publish_date[1] : undefined,
    };
    delete params.publish_date;
    fetchBooks(params);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    fetchBooks();
  };

  // 新增图书
  const handleAdd = () => {
    history.push('/books/create');
  };

  // 编辑图书
  const handleEdit = (id: number) => {
    history.push(`/books/edit/${id}`);
  };

  // 查看详情
  const handleView = (id: number) => {
    history.push(`/books/detail/${id}`);
  };

  // 删除图书
  const handleDelete = (id: number) => {
    setDeleteBookId(id);
    setDeleteModalVisible(true);
  };

  // 确认删除
  const confirmDelete = async () => {
    if (deleteBookId === null) return;

    try {
      await deleteBook(deleteBookId);
      message.success('删除成功');
      setDeleteModalVisible(false);
      fetchBooks();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 上传封面
  const handleUpload: UploadProps['onChange'] = ({ fileList }) => {
    setUploadFileList(fileList);
  };

  // 提交新增图书
  const handleCreateBook = async (values: any) => {
    try {
      const formData = new FormData();
      Object.keys(values).forEach(key => {
        if (values[key] !== undefined && values[key] !== null) {
          formData.append(key, values[key]);
        }
      });

      if (uploadFileList.length > 0) {
        formData.append('cover_image', uploadFileList[0].originFileObj);
      }

      await createBook(formData);
      message.success('添加成功');
      setUploadModalVisible(false);
      createBookForm.resetFields();
      setUploadFileList([]);
      fetchBooks();
    } catch (error) {
      message.error('添加失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '书名',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: BookItem) => (
        <a onClick={() => handleView(record.id)}>{text}</a>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: 'ISBN',
      dataIndex: 'isbn',
      key: 'isbn',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: any) => category?.name || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          available: { color: 'green', text: '可借阅' },
          borrowed: { color: 'orange', text: '已借出' },
          reserved: { color: 'blue', text: '已预约' },
          damaged: { color: 'red', text: '损坏' },
          lost: { color: 'purple', text: '丢失' },
        };
        const statusInfo = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      },
    },
    {
      title: '出版日期',
      dataIndex: 'publish_date',
      key: 'publish_date',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: BookItem) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record.id)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col span={24}>
            <Form
              form={searchForm}
              layout="inline"
              onFinish={handleSearch}
            >
              <Form.Item name="title" label="书名">
                <Input placeholder="请输入书名" style={{ width: 200 }} />
              </Form.Item>
              <Form.Item name="author" label="作者">
                <Input placeholder="请输入作者" style={{ width: 200 }} />
              </Form.Item>
              <Form.Item name="category" label="分类">
                <Select
                  placeholder="请选择分类"
                  style={{ width: 200 }}
                  allowClear
                >
                  {/* {categories.map(category => (
                    <Option key={category.id} value={category.id}>
                      {category.name}
                    </Option>
                  ))} */}
                </Select>
              </Form.Item>
              <Form.Item name="status" label="状态">
                <Select
                  placeholder="请选择状态"
                  style={{ width: 150 }}
                  allowClear
                >
                  <Option value="available">可借阅</Option>
                  <Option value="borrowed">已借出</Option>
                  <Option value="reserved">已预约</Option>
                  <Option value="damaged">损坏</Option>
                  <Option value="lost">丢失</Option>
                </Select>
              </Form.Item>
              <Form.Item name="publish_date" label="出版日期">
                <RangePicker style={{ width: 240 }} />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    搜索
                  </Button>
                  <Button onClick={handleReset}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Col>
        </Row>

        <div style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleAdd}
          >
            添加图书
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={books}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination({
                ...pagination,
                current: page,
                pageSize: pageSize,
              });
            },
          }}
        />
      </Card>

      {/* 删除确认模态框 */}
      <Modal
        title="确认删除"
        open={deleteModalVisible}
        onOk={confirmDelete}
        onCancel={() => setDeleteModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <p>确定要删除这本图书吗？此操作不可恢复。</p>
      </Modal>

      {/* 快速添加模态框 */}
      <Modal
        title="快速添加图书"
        open={uploadModalVisible}
        onCancel={() => {
          setUploadModalVisible(false);
          createBookForm.resetFields();
          setUploadFileList([]);
        }}
        footer={null}
        width={600}
      >
        <Form
          form={createBookForm}
          layout="vertical"
          onFinish={handleCreateBook}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="书名"
                rules={[{ required: true, message: '请输入书名' }]}
              >
                <Input placeholder="请输入书名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="author"
                label="作者"
                rules={[{ required: true, message: '请输入作者' }]}
              >
                <Input placeholder="请输入作者" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="isbn"
                label="ISBN"
                rules={[{ required: true, message: '请输入ISBN' }]}
              >
                <Input placeholder="请输入ISBN" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="publisher"
                label="出版社"
                rules={[{ required: true, message: '请输入出版社' }]}
              >
                <Input placeholder="请输入出版社" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="publish_date"
                label="出版日期"
                rules={[{ required: true, message: '请选择出版日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="分类"
                rules={[{ required: true, message: '请选择分类' }]}
              >
                <Select placeholder="请选择分类">
                  {/* {categories.map(category => (
                    <Option key={category.id} value={category.id}>
                      {category.name}
                    </Option>
                  ))} */}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="language"
                label="语言"
                initialValue="中文"
              >
                <Select>
                  <Option value="中文">中文</Option>
                  <Option value="英文">英文</Option>
                  <Option value="日文">日文</Option>
                  <Option value="其他">其他</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="page_count"
                label="页数"
              >
                <Input type="number" placeholder="请输入页数" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={4} placeholder="请输入图书描述" />
          </Form.Item>

          <Form.Item
            name="cover_image"
            label="封面图片"
          >
            <Upload
              fileList={uploadFileList}
              onChange={handleUpload}
              maxCount={1}
              listType="picture-card"
            >
              {uploadFileList.length < 1 && (
                <button style={{ border: 0, background: 'none' }} type="button">
                  <UploadOutlined />
                  <div style={{ marginTop: 8 }}>上传封面</div>
                </button>
              )}
            </Upload>
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                添加
              </Button>
              <Button onClick={() => {
                setUploadModalVisible(false);
                createBookForm.resetFields();
                setUploadFileList([]);
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BookList;